package com.ljkj.cordial.chat.util;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 处理子线程业务工具
 */
public class ObserverThread {


    private static class BUILD {
        private static ObserverThread INSTANCE = new ObserverThread();
    }

    public static ObserverThread create() {
        return BUILD.INSTANCE;
    }

    private ExecutorService cachedThreadPool;

    public void onBackGroudThread(Runnable runnable) {
        if (cachedThreadPool == null || cachedThreadPool.isShutdown()) {
            cachedThreadPool = Executors.newCachedThreadPool();
        }
        cachedThreadPool.execute(runnable);
    }

    public <T> ObserverThread onNextThread0(OnActionListener<T> actionListener) {
        if (actionListener == null) {
            return this;
        }
        if (cachedThreadPool == null || cachedThreadPool.isShutdown()) {
            cachedThreadPool = Executors.newCachedThreadPool();
        }

        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                Handler mainHandler;
                try {
                    Object obj = actionListener.onThreadAction();
                    if (!cachedThreadPool.isShutdown()) {
                        if (Looper.myLooper() == null) {
                            Looper.prepare();
                        }
                        mainHandler = new Handler(Looper.getMainLooper()) {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                try {
                                    actionListener.onAction((T) obj);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    removeCallbacks(null);
                                }

                            }
                        };
                        Looper.myLooper().quit();
                        mainHandler.sendEmptyMessage(0);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mainHandler = null;
                }
            }
        });
        return BUILD.INSTANCE;
    }

    public ObserverThread onNextThread1(OnMulActionListener actionListener) {
        if (actionListener == null) {
            return this;
        }
        if (cachedThreadPool == null || cachedThreadPool.isShutdown()) {
            cachedThreadPool = Executors.newCachedThreadPool();
        }
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                Handler mainHandler;
                try {
                    Object[] obj = actionListener.onThreadAction();
                    if (!cachedThreadPool.isShutdown()) {
                        if (Looper.myLooper() == null) {
                            Looper.prepare();
                        }
                        mainHandler = new Handler(Looper.getMainLooper()) {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                try {
                                    actionListener.onAction(obj);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    removeCallbacks(null);
                                }
                            }
                        };
                        Looper.myLooper().quit();
                        mainHandler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mainHandler = null;
                }
            }
        });
        return BUILD.INSTANCE;
    }

    public <T> ObserverThread onNextThread2(OnListActionListener<T> actionListener) {
        if (actionListener == null) {
            return this;
        }
        if (cachedThreadPool == null || cachedThreadPool.isShutdown()) {
            cachedThreadPool = Executors.newCachedThreadPool();
        }
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                Handler mainHandler;
                try {
                    List<T> list = actionListener.onThreadAction();
                    if (!cachedThreadPool.isShutdown()) {
                        if (Looper.myLooper() == null) {
                            Looper.prepare();
                        }
                        mainHandler = new Handler(Looper.getMainLooper()) {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                try {
                                    actionListener.onAction(list);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    removeCallbacks(null);
                                }
                            }
                        };
                        Looper.myLooper().quit();

                        mainHandler.sendEmptyMessage(0);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mainHandler = null;
                }
            }
        });
        return BUILD.INSTANCE;
    }

    public void shutdownThread() {
        if (cachedThreadPool != null && !cachedThreadPool.isShutdown()) {
            cachedThreadPool.shutdown();
        }
    }

    public interface OnActionListener<T> {
        void onAction(T obj);

        T onThreadAction();
    }

    public interface OnMulActionListener {
        void onAction(Object... obj);

        Object[] onThreadAction();
    }

    public interface OnListActionListener<T> {
        void onAction(List<T> list);

        List<T> onThreadAction();
    }

    public static void registerRefreshData(Context context, OnBroadcastRefreshListener refreshListener) {
        IntentFilter filter = new IntentFilter(Canstants.ACTION_REFRESH_DATA);
        BUILD.INSTANCE.refreshListener = refreshListener;
        context.registerReceiver(receiver, filter);
    }

    public static void unregisterRefreshData(Context context) {
        context.unregisterReceiver(receiver);
        BUILD.INSTANCE.refreshListener = null;
    }

    public static void sendRefreshAction() {
        Intent intent = new Intent(Canstants.ACTION_REFRESH_DATA);
        ChatApp.getInstance().sendBroadcast(intent);
    }

    private static BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BUILD.INSTANCE.refreshListener != null) {
                BUILD.INSTANCE.refreshListener.onRefresh(context, intent);
            }
        }
    };
    private OnBroadcastRefreshListener refreshListener;

    public interface OnBroadcastRefreshListener {
        void onRefresh(Context context, Intent intent);
    }
}
